import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { showWarning } from '../components/layout/GlobalNotification.vue'
import {
    loginAPI, logoutAPI, loginUserInfoAPI, refreshAccessTokenAPI,
    type LoginParams as APILoginParams,
} from '../api/auth'
import { useMenuStore } from './menu'

// 统一的用户详细信息界面
interface UserDetail {
    userId: string;
    username: string;
    nickName?: string;
    avatar?: string;
    email?: string;
    phonenumber?: string;
    sex?: string;
    roles?: string[];
    permissions?: Record<string, string[]>;
    loginTime?: number;
    ipaddr?: string;
    loginLocation?: string;
}

export const useUserStore = defineStore('user', () => {

    // State 现在使用统一的 UserDetail 结构
    const userDetail = ref<UserDetail>({
        userId: '',
        username: '',
        roles: [],
        permissions: {}
    })

    // 令牌和身份验证状态
    const accessToken = ref('')
    const refreshToken = ref('')
    const lastActivity = ref(Date.now())
    const isLoggedIn = ref(false)

    // 计算属性
    const isAuthenticated = computed(() => isLoggedIn.value && !!accessToken.value)
    const userId = computed(() => userDetail.value.userId)
    const username = computed(() => userDetail.value.username)
    const nickname = computed(() => userDetail.value.nickName || userDetail.value.username)
    const avatar = computed(() => userDetail.value.avatar || '')
    const roles = computed(() => userDetail.value.roles || [])
    const permissions = computed(() => userDetail.value.permissions || {})
    const email = computed(() => userDetail.value.email || '')
    const phonenumber = computed(() => userDetail.value.phonenumber || '')
    const sex = computed(() => userDetail.value.sex || '')
    const loginTime = computed(() => userDetail.value.loginTime || 0)
    const ipaddr = computed(() => userDetail.value.ipaddr || '')
    const loginLocation = computed(() => userDetail.value.loginLocation || '')

    // 定时器
    let refreshTokenInterval: number | null = null
    let inactivityTimer: number | null = null

    // 初始化用户状态
    const initUserState = () => {
        const storedAccessToken = localStorage.getItem('accessToken')
        const storedRefreshToken = localStorage.getItem('refreshToken')
        const storedUserDetail = localStorage.getItem('userDetail')

        if (storedAccessToken) {
            accessToken.value = storedAccessToken
            isLoggedIn.value = true
        }

        if (storedRefreshToken) {
            refreshToken.value = storedRefreshToken
        }

        try {
            if (storedUserDetail) {
                userDetail.value = JSON.parse(storedUserDetail)
            }
        } catch (error) {
            console.error('无法解析 localStorage 中的用户数据:', error)
            clearUserData()
        }

        if (isLoggedIn.value) {
            startTokenRefresh()
            startInactivityTracking()
        }
    }

    // 统一用户详细信息更新
    const updateUserDetail = (newDetail: Partial<UserDetail>) => {
        userDetail.value = {
            ...userDetail.value,
            ...newDetail
        }
        saveToLocalStorage()
    }

    // 登录处理程序
    const handleLogin = async (params: APILoginParams) => {
        try {
            // 先清除可能存在的上一个用户的菜单和路由数据
            const menuStore = useMenuStore()
            menuStore.clearMenuStorage()
            menuStore.resetMenuState()
            
            // 记录新的登录时间戳
            const loginTimestamp = Date.now().toString()
            localStorage.setItem('current_login_timestamp', loginTimestamp)
            
            const res = await loginAPI(params)

            if (res.code === 200 && res.tokenInfo) {
                setTokens(res.tokenInfo.accessToken, res.tokenInfo.refreshToken)
                await fetchUserInfo()
                return {
                    success: true,
                    message: res.msg,
                    data: {
                        ip: res.ip,
                        ...res.tokenInfo,
                        userInfo: userDetail.value
                    }
                }
            }
            return { success: false, message: res.msg || '登录失败' }
        } catch (error: any) {
            console.error('登录错误:', error)
            return {
                success: false,
                message: error.response?.data?.msg || '登录请求失败'
            }
        }
    }

    // 从 API 获取用户信息
    const fetchUserInfo = async () => {
        try {
            const res = await loginUserInfoAPI()
            if (res.code === 200 && res.userInfo) {
                const apiUserDetail: UserDetail = {
                    userId: res.userInfo.userId,
                    username: res.userInfo.username,
                    nickName: res.userInfo.user?.nickName,
                    avatar: res.userInfo.user?.avatar,
                    email: res.userInfo.user?.email,
                    phonenumber: res.userInfo.user?.phonenumber,
                    sex: res.userInfo.user?.sex,
                    roles: res.userInfo.roles,
                    permissions: res.userInfo.permissions,
                    loginTime: res.userInfo.loginTime,
                    ipaddr: res.userInfo.ipaddr,
                    loginLocation: res.userInfo.loginLocation
                }

                updateUserDetail(apiUserDetail)
                return { success: true, data: apiUserDetail }
            }
            return { success: false, message: res.msg }
        } catch (error) {
            console.error('无法获取用户信息:', error)
            return { success: false, message: '请求失败' }
        }
    }

    // 保存到 localStorage
    const saveToLocalStorage = () => {
        localStorage.setItem('userDetail', JSON.stringify(userDetail.value))
    }

    // Token 管理
    const setTokens = (newAccessToken: string, newRefreshToken: string) => {
        accessToken.value = newAccessToken
        refreshToken.value = newRefreshToken
        isLoggedIn.value = true
        localStorage.setItem('accessToken', newAccessToken)
        localStorage.setItem('refreshToken', newRefreshToken)
        startTokenRefresh()
        startInactivityTracking()
    }

    // 刷新令牌
    const refreshAccessToken = async () => {
        // 如果已经退出登录或没有刷新令牌，立即返回
        if (!refreshToken.value || !isLoggedIn.value) return false

        try {
            const res = await refreshAccessTokenAPI(refreshToken.value)
            if (res.code === 200 && res.data?.accessToken) {
                accessToken.value = res.data.accessToken
                localStorage.setItem('accessToken', accessToken.value)
                return true
            }
            // 如果刷新失败，但不是因为已调用logout，才执行logout
            if (isLoggedIn.value) {
                console.warn('令牌刷新失败，执行自动注销')
                // 使用一个专门的方法处理令牌失效，避免循环调用
                handleTokenExpired('会话已过期，请重新登录')
            }
            return false
        } catch (error) {
            console.error('令牌刷新失败:', error)
            // 使用一个专门的方法处理令牌失效，避免循环调用
            if (isLoggedIn.value) {
                handleTokenExpired('会话已过期，请重新登录')
            }
            return false
        }
    }

    // 处理令牌过期，避免循环调用
    const handleTokenExpired = (message?: string) => {
        // 确保只清除状态，不再触发API调用
        stopTokenRefresh()
        stopInactivityTracking()
        
        // 清除所有令牌和状态
        accessToken.value = ''
        refreshToken.value = ''
        isLoggedIn.value = false
        userDetail.value = {
            userId: '',
            username: '',
            roles: [],
            permissions: {}
        }
        
        // 清除本地存储
        localStorage.removeItem('accessToken')
        localStorage.removeItem('refreshToken')
        localStorage.removeItem('userDetail')
        
        // 清除面包屑数据
        localStorage.removeItem('breadcrumb_tags')
        localStorage.removeItem('breadcrumb_tags_timestamp')
        
        // 清除菜单和路由数据
        const menuStore = useMenuStore()
        menuStore.clearMenuStorage()
        
        // 显示消息
        message && showWarning(message)
    }

    // 注销 - 同步版本，确保数据清除完成后再执行后续操作
    const logout = async (message?: string) => {
        // 立即停止所有定时器，避免在注销过程中继续尝试刷新令牌
        stopTokenRefresh()
        stopInactivityTracking()
        
        // 先同步清除菜单和路由数据
        const menuStore = useMenuStore()
        menuStore.resetMenuState() // 这会同步重置状态和清除存储
        
        // 清除面包屑数据
        localStorage.removeItem('breadcrumb_tags')
        localStorage.removeItem('breadcrumb_tags_timestamp')
        
        // 清除用户数据
        clearUserData()
        
        try {
            // 注销前保存当前token以便于API调用，但确保不会触发自动刷新
            const token = accessToken.value
            
            // 确保变量已经清除
            accessToken.value = ''
            refreshToken.value = ''
            isLoggedIn.value = false
            
            // 然后异步调用登出API时使用已保存的token
            if (token) {
                await logoutAPI()
            }
        } catch (error) {
            console.error('注销API调用失败:', error)
        } finally {
            // 再次确保清除完成
            const menuStore = useMenuStore()
            menuStore.clearMenuStorage()

            // 显示消息
            message && showWarning(message)
        }
    }

    // 清除用户数据
    const clearUserData = () => {
        // 先停止所有定时器，避免清除数据后还在执行刷新
        stopTokenRefresh()
        stopInactivityTracking()
        
        accessToken.value = ''
        refreshToken.value = ''
        isLoggedIn.value = false
        userDetail.value = {
            userId: '',
            username: '',
            roles: [],
            permissions: {}
        }

        localStorage.removeItem('accessToken')
        localStorage.removeItem('refreshToken')
        localStorage.removeItem('userDetail')
        
        // 确保清除面包屑数据
        localStorage.removeItem('breadcrumb_tags')
        localStorage.removeItem('breadcrumb_tags_timestamp')
        
        // 清除登录时间戳，确保重新登录时面包屑被重置
        localStorage.removeItem('login_timestamp')
    }

    // 令牌刷新计时器
    const startTokenRefresh = () => {
        stopTokenRefresh()
        // 确保有令牌且用户已登录
        if (!refreshToken.value || !isLoggedIn.value) return

        refreshTokenInterval = window.setInterval(async () => {
            // 每次刷新前检查登录状态
            if (!isLoggedIn.value) {
                console.log('用户已登出，终止令牌刷新')
                stopTokenRefresh()
                return
            }
            
            try {
                const success = await refreshAccessToken()
                if (!success) {
                    console.warn('令牌刷新失败，停止自动刷新')
                    stopTokenRefresh()
                }
            } catch (error) {
                console.error('自动刷新错误:', error)
                stopTokenRefresh()
            }
        }, 27 * 60 * 1000) // 27 minutes
    }

    // 停止令牌刷新
    const stopTokenRefresh = () => {
        if (refreshTokenInterval) {
            clearInterval(refreshTokenInterval)
            refreshTokenInterval = null
            console.log('令牌自动刷新已停止')
        }
    }

    // 活动跟踪
    const updateLastActivity = () => lastActivity.value = Date.now()

    const startInactivityTracking = () => {
        const events: Array<keyof WindowEventMap> = ['mousemove', 'keydown', 'click', 'scroll']
        events.forEach(e => window.addEventListener(e, updateLastActivity))

        inactivityTimer = window.setInterval(() => {
            if (Date.now() - lastActivity.value > 30 * 60 * 1000) {
                logout('长时间处于非活动状态，自动注销')
            }
        }, 60_000)
    }

    // 停止不活跃追踪
    const stopInactivityTracking = () => {
        if (inactivityTimer !== null) {
            clearInterval(inactivityTimer)
            inactivityTimer = null
            console.log('不活跃追踪已停止')
        }
        
        // 同时移除所有相关事件监听器
        if (typeof window !== 'undefined') {
            const events: Array<keyof WindowEventMap> = ['mousemove', 'keydown', 'click', 'scroll']
            events.forEach(e => window.removeEventListener(e, updateLastActivity))
            console.log('所有不活跃监听器已移除')
        }
    }

    return {
        // 状态
        accessToken,
        refreshToken,
        userDetail,
        isAuthenticated,

        // 计算
        userId,
        username,
        nickname,
        avatar,
        roles,
        permissions,
        email,
        phonenumber,
        sex,
        loginTime,
        ipaddr,
        loginLocation,

        // 方法
        initUserState,
        handleLogin,
        fetchUserInfo,
        logout,
        refreshAccessToken,
        updateUserDetail
    }
})